package database

import (
	"database/sql"
	"fmt"
	"log"
	"time"

	"learn-go-demo/pkg/config"

	_ "github.com/go-sql-driver/mysql"
)

// NewMySQLConnection 创建 MySQL 数据库连接
func NewMySQLConnection(dbConfig config.DatabaseConfig) (*sql.DB, error) {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		dbConfig.User,
		dbConfig.Password,
		dbConfig.Host,
		dbConfig.Port,
		dbConfig.Database,
	)

	db, err := sql.Open("mysql", dsn)
	if err != nil {
		return nil, fmt.Errorf("failed to open database: %w", err)
	}

	// 配置连接池
	db.SetMaxOpenConns(dbConfig.MaxOpenConns)
	db.SetMaxIdleConns(dbConfig.MaxIdleConns)
	db.SetConnMaxLifetime(time.Duration(dbConfig.ConnMaxLifetime) * time.Minute)

	// 测试连接
	if err := db.Ping(); err != nil {
		return nil, fmt.Errorf("failed to ping database: %w", err)
	}

	log.Printf("Successfully connected to MySQL database at %s:%d/%s",
		dbConfig.Host, dbConfig.Port, dbConfig.Database)
	return db, nil
}

// NewMySQLConnectionFromConfig 从全局配置创建数据库连接
func NewMySQLConnectionFromConfig() (*sql.DB, error) {
	dbConfig := config.GetDatabaseConfig()
	return NewMySQLConnection(dbConfig)
}
